<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <link rel="stylesheet" type="text/css" th:href="@{/plugins/layui/css/layui.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/css/client.css}">
    <style>
        .layui-form-item .layui-input-inline {
            width: 150px;
        }
        .online-people div{
            height: 20px;
            line-height: 20px;
            background-color: #FFB800;
            padding: 5px;
            margin: 5px;
        }
        .sys-msg div{
            height: 20px;
            line-height: 20px;
            background-color: #D0D0D0;
            padding: 5px;
            margin: 5px;
        }
    </style>
    <script th:inline="javascript">
        var user = [[${user}]]
    </script>
</head>
<body>
<div class="layui-container">
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 25px;">
        <legend style="margin-left: 40%;">聊天室</legend>
    </fieldset>
    <div class="layui-row layui-col-space5">
        <div class="layui-col-md3">
            <blockquote class="layui-elem-quote">当前用户</blockquote>
            <form class="layui-form">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">用户Id</label>
                        <div class="layui-input-inline">
                            <input autocomplete="off" class="layui-input" th:value="${{user.userId}}">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">用户名</label>
                        <div class="layui-input-inline">
                            <input autocomplete="off" class="layui-input" th:value="${{user.userName}}">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <button class="layui-btn" onclick="openJoinDialog()" type="button">加入房间</button>
                        <button class="layui-btn layui-btn-danger" onclick="SOCKET.exit()" type="button">退出房间</button>
                    </div>
                </div>
            </form>
        </div>
        <div class="layui-col-md6">
            <blockquote class="layui-elem-quote">接收信息区</blockquote>
            <fieldset class="layui-elem-field layui-field-title">
                <legend>消息记录</legend>
            </fieldset>
            <div class="layui-tab layui-tab-card" style="height: 200px;">
                <div id="msgDiv" class="scroller">

                </div>
            </div>
        </div>
        <div class="layui-col-md3">
            <blockquote class="layui-elem-quote">在线人数</blockquote>
            <div class="online-people">

            </div>
            <blockquote class="layui-elem-quote">系统消息</blockquote>
            <div class="sys-msg">

            </div>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-xs12">
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">消息</label>
                <div class="layui-input-block">
                    <textarea placeholder="请输入内容" class="layui-textarea" id="msg"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn layui-btn-normal" onclick="SOCKET.sendMsg()">发送消息</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="application/javascript" th:src="@{/javascript/jquery-2.1.4.js}"></script>
<!--layui-->
<script type="application/javascript" th:src="@{/plugins/layui/layui.js}"></script>
<!--加入房间弹窗-->
<div id="joinRoomDialog" style="display: none;padding: 15px">
    <form class="layui-form" id="userForm">
        <div class="layui-form-item">
            <label class="layui-form-label">当前用户ID:</label>
            <div class="layui-input-block">
                <input type="text" autocomplete="off" class="layui-input" disabled th:value="${{user.userId}}">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">房间号:</label>
            <div class="layui-input-block">
                <input type="text" id="roomId" autocomplete="off" placeholder="请输入房间号" class="layui-input">
            </div>
        </div>
    </form>
</div>


<script>
    var ws = null;
    var layer = null;
    var roomId = null;

    $(function () {
        Layui.init();
    });

    var Layui = {
        /**
         * 初始化layui
         */
        init: () => {
            layui.use(['layer'], function () {
                layer = layui.layer;
            });
        }
    }

    /**
     * WebSocket 相关
     */
    var SOCKET = {
        /**
         * 存放消息div
         */
        $msgDiv: $("#msgDiv"),
        /**
         * websocket对象
         */
        ws: null,
        /**
         * websocket 连接地址
         */
        url: "" + window.location.protocol + "//" + window.location.host + "/chat/",
        /**
         * 开始建立连接
         * @returns {boolean}
         */
        join: () => {
            if (typeof (WebSocket) == "undefined") {
                layer.msg('您的浏览器不支持WebSocket', {icon: 5, time: 1500})
                return false;
            }
            roomId = $("#roomId").val();
            if (roomId === '' || roomId == null) {
                layer.msg('请输入房间号', {icon: 5, time: 1500})
                return false;
            }
            SOCKET.url = SOCKET.url.replace("https", "ws").replace("http", "ws");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
            if (SOCKET.ws != null) {
                SOCKET.ws.close();
                SOCKET.ws = null;
            }
            SOCKET.ws = new WebSocket(SOCKET.url + roomId + '/' + user.userId);
            //打开事件
            SOCKET.ws.onopen = SOCKET.onOpen;
            //关闭事件
            SOCKET.ws.onclose = SOCKET.onClose;
            //发生了错误事件
            SOCKET.ws.onerror = SOCKET.onError;
            // 接收消息
            SOCKET.ws.onmessage = SOCKET.onMessage;
        },
        /**
         * 成功建立
         */
        onOpen: () => {
            layer.msg('连接成功', {icon: 1, time: 1500}, () => {
                // 获取 房间所有人
                setTimeout(() => {
                    SOCKET.getRoomList()
                }, 1000);
            });

        },
        /**
         * 接收服务端推送消息
         */
        onMessage: (msg) => {
            msg = JSON.parse(msg.data)
            // 系统消息
            if (msg.sysMsgType === 'join') {
                $('.sys-msg').append(
                    '<div> ' + msg.data + ' 加入了房间</div>'
                );
                if($(msg.data).length === 0){
                    $('.online-people').append(
                        '<div id="'+msg.data+'"> 用户名：' + msg.data + ' </div>'
                    );
                }
            }
            if (msg.sysMsgType === 'leave') {
                $('.sys-msg').append(
                    '<div> ' + msg.data + ' 离开了房间 </div>'
                );
                $('#'+msg.data).remove();
            }
            // 房间信息
            if (msg.sysMsgType === 'roomList') {
                $('.online-people').empty();
                msg.data.forEach(item => {
                    $('.online-people').append(
                        '<div id="'+item.userId+'"> 用户名：' + item.userId + ' </div>'
                    );
                })
            }
            //  普通文本信息
            if (msg.sysMsgType === 'text') {
                SOCKET.$msgDiv.append('' +
                    '<div class="other-msg-container">' +
                    '   <img class="left-img" src="../images/left.png">' +
                    '   <div class="other-msg msg-common">' +
                    '       <p class="user">用户名：' + msg.sender + '</p><p class="chat">' + msg.data + '</p>' +
                    '   </div>' +
                    '</div>');
                SOCKET.scroolBottom();
            }
        },
        /**
         * 连接发生错误
         */
        onError: () => {
            layer.msg('websocket发生了错误', {icon: 5, time: 1500})
        },
        /**
         * 连接关闭
         */
        onClose: () => {
            layer.msg('websocket已关闭', {icon: 5, time: 1500})
        },
        /**
         * 发送消息
         */
        sendMsg: () => {
            var msg = $("#msg").val();
            if (msg === '' || msg == null) {
                layer.msg('消息内容不能为空', {icon: 5, time: 1500});
                return;
            }
            var msgObj = {
                sender: user.userId,
                roomId: roomId,
                sysMsgType: 'text',
                data: msg
            };
            if (SOCKET.ws && SOCKET.ws.readyState === 1) {
                SOCKET.ws.send(JSON.stringify(msgObj));
                SOCKET.$msgDiv.append('' +
                    '<div class="my-msg-container">' +
                    '   <img class="right-img" src="/images/right.png">' +
                    '   <div class="my-msg msg-common">' +
                    '       <p class="user">用户名：' + user.userId + '</p><p class="chat">' + msg + '</p>' +
                    '   </div>' +
                    '</div>');
                SOCKET.scroolBottom();
                $("#msg").val('')
            } else {
                layer.msg('请检查连接是否正常？', {icon: 5, time: 1500});
            }
        },
        /**
         * 滚动至底部
         */
        scroolBottom: () => {
            var $div = document.getElementById("msgDiv");
            $div.scrollTop = $div.scrollHeight;
        },
        /**
         * 断开连接
         */
        disConnect: () => {
            if (SOCKET.ws) {
                SOCKET.ws.close();
            }
        },
        /**
         * 退出房间
         */
        exit: () => {
            layer.confirm('确定是否退出房间？', {title: '提示'}, function (index) {
                SOCKET.disConnect();
                $('.sys-msg').empty();
                $('.online-people').empty();
                $('#msgDiv').empty();
            });
        },
        /**
         * 获取房间人列表
         */
        getRoomList() {
            var msgObj = {
                sysMsgType: 'roomList',
                sender: user.userId,
                roomId: roomId
            }
            if (SOCKET.ws && SOCKET.ws.readyState === 1) {
                SOCKET.ws.send(JSON.stringify(msgObj));
            } else {
                layer.msg('请检查连接是否正常？', {icon: 5, time: 1500});
            }
        }
    }

    window.onbeforeunload = function () {
        SOCKET.disConnect();
    }

    /**
     * 打开加入房间弹窗
     */
    function openJoinDialog() {
        layer.open({
            id: 'add',
            type: 1,
            title: ['加入房间'],
            skin: 'layui-layer-molv',
            area: '500px',
            offset: 'auto',
            content: $('#joinRoomDialog'),
            btn: ['提交', '取消'],
            yes: (index, layero) => {
                SOCKET.join();
                layer.close(index)
            }, cancle: (index, layero) => {
                layer.close(index);
            }
        })
    }
</script>
</body>
</html>
